using System;
using System.IO;
using System.Windows;
using WinForms = System.Windows.Forms;

namespace DownloadTool
{
    /// <summary>
    /// SettingsDialog.xaml 的交互逻辑
    /// </summary>
    public partial class SettingsDialog : Window
    {
        public SettingsDialog()
        {
            InitializeComponent();
            
            // Load current settings
            DefaultPathTextBox.Text = AppSettings.Instance.DefaultDownloadPath;
            
            // Ensure the path is displayed
            Loaded += (s, e) => {
                DefaultPathTextBox.Text = AppSettings.Instance.DefaultDownloadPath;
            };
        }

        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            using var dialog = new WinForms.FolderBrowserDialog();
            dialog.Description = "选择默认下载位置";
            dialog.SelectedPath = DefaultPathTextBox?.Text ?? string.Empty;
            
            if (dialog.ShowDialog() == WinForms.DialogResult.OK && DefaultPathTextBox != null)
            {
                DefaultPathTextBox.Text = dialog.SelectedPath;
            }
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (DefaultPathTextBox == null) return;
            
            string path = DefaultPathTextBox.Text.Trim();
            
            if (string.IsNullOrEmpty(path))
            {
                System.Windows.MessageBox.Show("请选择有效的保存位置。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // Create directory if it doesn't exist
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                
                // Save settings
                AppSettings.Instance.DefaultDownloadPath = path;
                AppSettings.Instance.Save();
                
                DialogResult = true;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"无法创建目录: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }
    }
}